package com.by.basicgateway.nacoslistener;

import com.alibaba.fastjson2.JSON;
import com.alibaba.nacos.client.naming.event.InstancesChangeEvent;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.stereotype.Component;

/**
 * @author Tian Wei
 * @version 1.0
 * @date 2024/2/6 5:06 PM
 */
@Slf4j
@Component
public class NacosGatewayInstanceChangeListener extends Subscriber<InstancesChangeEvent> {

    @Autowired
    private LoadBalancerClientFactory clientFactory;

    @PostConstruct
    public void registerToNotifyCenter() {
        NotifyCenter.registerSubscriber(this);
    }

    @Override
    public void onEvent(InstancesChangeEvent event) {

//        String serviceName = event.getServiceName();
//        ServiceInstanceListSupplier oldServiceInstanceListSupplier = clientFactory.getLazyProvider(serviceName, ServiceInstanceListSupplier.class).getIfAvailable();
//        oldServiceInstanceListSupplier.get().last().subscribe(items -> log.info("[NacosGatewayInstanceChangeListener][onEvent] 服务列表发生变更,old服务名称:{},old服务列表为:{}", serviceName, JSON.toJSONString(items)));
//
//        Map<String, AnnotationConfigApplicationContext> contextsMap = (Map<String, AnnotationConfigApplicationContext>) ReflectUtil.getFieldValue(clientFactory, "contexts");
//        if (contextsMap.containsKey(serviceName)) {
//            contextsMap.get(serviceName).close();
//            contextsMap.remove(serviceName);
//            clientFactory.getInstances(serviceName, LoadBalancerLifecycle.class);
//        }
//        //延时10秒打印新日志
//        Mono.just(clientFactory.getLazyProvider(serviceName, ServiceInstanceListSupplier.class).getIfAvailable().get().toStream().findFirst().orElse(Collections.EMPTY_LIST))
//                .delaySubscription(Duration.ofSeconds(10L))
//                .doOnNext(items -> log.info("[NacosGatewayInstanceChangeListener][onEvent] 服务列表发生变更,new服务名称:{},new服务列表为:{}", serviceName, JSON.toJSONString(items)))
//                .subscribe();

        //刷新 CachingServiceInstanceListSupplier
        //刷新 DefaultLoadBalancerCacheManager
        //刷新 ByRoundRobinLoadBalancer
        log.info("[NacosGatewayInstanceChangeListener][onEvent] 服务变更通知通知:{},{}", event.getServiceName(), JSON.toJSONString(event));
    }

    @Override
    public Class<? extends Event> subscribeType() {
        return InstancesChangeEvent.class;
    }
}
